package com.rem.concurrency.multithreading.use;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;

/**
 * 信号灯法
 *
 * @author Rem
 * @date 2021-03-05
 */

public class TestPc2 {

    public static void main(String[] args) {
        TV tv = new TV();
        new Actor(tv).start();
        new Watcher(tv).start();
    }


}

@Data
@AllArgsConstructor
class Actor extends Thread {

    TV tv;

    @Override
    public void run() {
        for (int i = 0; i < 24; i++) {
            if (i % 2 == 0) {
                this.tv.show("快乐大本营");
            } else {
                this.tv.show("庆余年");
            }
        }
    }
}

@Data
@AllArgsConstructor
class Watcher extends Thread {

    TV tv;

    @Override
    public void run() {
        for (int i = 0; i < 24; i++) {
            tv.wathcer();
        }
    }
}


/**
 * 观看电视节目
 */
@Data
class TV {

    /**
     * 电视节目
     */
    private String program;

    /**
     * 标志位
     */
    private Boolean flag = true;


    @SneakyThrows
    public synchronized void show(String program) {
        if (!flag) {
            this.wait();
        }
        System.out.println("演员表演了:" + program);
        this.program = program;
        this.flag = !this.flag;
        this.notify();
    }


    @SneakyThrows
    public synchronized void wathcer() {

        if (flag) {
            this.wait();
        }
        System.out.println("观看了：" + program);
        this.flag = !this.flag;
        this.notify();
    }

}

